

package yf.mall.service.impl;
import com.yf.response.RRException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.excel.EasyExcel;
import yf.mall.utils.PushUtil;
import yf.mall.dao.UserDao;
import yf.mall.entity.UserEntity;
import  yf.mall.vo.down.LiveDown;

import java.util.List;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
import java.util.stream.Collectors;
import yf.mall.dao.LiveDao;
import yf.mall.entity.LiveEntity;
import yf.mall.vo.LiveVo;
import yf.mall.service.LiveService;
import com.yf.service.impl.BaseServiceImpl;

/**
 * 账户记录Service实现类
 *
 *
 * 
 * @date Thu Sep 10 11:00:34 CST 2020
 */
@Service
public class LiveServiceImpl extends BaseServiceImpl<LiveEntity> implements LiveService {

    private LiveDao dao;
    @Autowired
    private UserDao userDao;
    @Value("${LIVE.PUSH_DOMAIN}")
    private String pushDomain;
    @Value("${LIVE.PULL_DOMAIN}")
    private String pullDomain;
    @Value("${LIVE.KEY}")
    private String key;
    @Autowired
    public void setDao(LiveDao dao) {
        this.dao = dao;
        super.setBaseDao(dao);
    }


    @Override
    public List<LiveVo> findVo(LiveVo vo){
        return dao.findVo(vo);
    }

    @Override
    public LiveVo getVo(Long id){
        return dao.getVo(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveVo(LiveVo vo) {
        //过期时间戳
        String streamName = vo.getLive().getStreamName();
        //生成推流地址
        long epoch =  vo.getLive().getEnd().getTime();
        String push = PushUtil.getSafeUrl(key,streamName , epoch/1000);
        push = pushDomain + streamName + "?" + push;
        vo.getLive().setPush(push);
        //拉流地址
        vo.getLive().setPull(pullDomain + streamName);
        if (vo.getLive().getUserCode() != null && !"".equals(vo.getLive().getUserCode())){
            UserEntity userEntity = userDao.findByCode(vo.getLive().getUserCode());
            if (userEntity == null){
                throw new RRException("该编号不存在");
            }
            vo.getLive().setUserId(userEntity.getId());
        }
        int save = dao.save(vo.getEntity());
        //保存直播对应的产品
        if (vo.getGoodsList() != null && vo.getGoodsList().size() > 0){
            for (Long goodsId : vo.getGoodsList()) {
                dao.saveGoods(vo.getEntity().getId(),goodsId);
            }
        }
        return save;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateVo(LiveVo vo){
        if (vo.getLive().getUserCode() != null && !"".equals(vo.getLive().getUserCode())){
            UserEntity userEntity = userDao.findByCode(vo.getLive().getUserCode());
            if (userEntity == null){
                throw new RRException("该编号不存在");
            }
            vo.getLive().setUserId(userEntity.getId());
        }
        //生成推流地址
        long epoch =  vo.getLive().getEnd().getTime();
        String streamName = vo.getLive().getStreamName();
        String push = PushUtil.getSafeUrl(key,streamName , epoch/1000);
        push = pushDomain + streamName + "?" + push;
        vo.getLive().setPush(push);
        //修改直播对应的产品
        if (vo.getGoodsList() != null && vo.getGoodsList().size() > 0){
            //先删后增
            dao.deleteByLiveId(vo.getLive().getId());
            for (Long goodsId : vo.getGoodsList()) {
               dao.saveGoods(vo.getLive().getId(),goodsId);
            }
        }
        return dao.update(vo.getEntity());
    }



    @Override
    public void downLoad(HttpServletResponse response, List<LiveVo> list) {
        try {
            List<LiveDown> datas = list.stream().map(item -> new LiveDown(item)).collect(Collectors.toList());
            response.setContentType("application/vnd.ms-excel" );
            response.setCharacterEncoding("utf-8" );
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8" );
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx" );
            EasyExcel.write(response.getOutputStream(), LiveDown.class).sheet("模板" ).doWrite(datas);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }




    /**内部方法**/
    @Override
    public List<Long> findByLiveId(Long liveId) {
        return dao.findByLiveId(liveId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByLiveId(Long[] ids) {
        dao.deleteByLiveIdBatch(ids);
        dao.deleteBatch(ids);
    }


    /**外部方法实现**/

    @Override
    public List<LiveEntity> getList() {
        return dao.getList();
    }

    @Override
    public List<Long> findByGoodsId(Long goodsId) {
        return dao.findByGoodsId(goodsId);
    }


}
